import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'main.dart';

/// 1. 定义状态对象，可以扩展多个字段
class HelloState {
  final String message;
  final int counter;

  const HelloState({
    required this.message,
    required this.counter,
  });

  HelloState copyWith({
    String? message,
    int? counter,
  }) {
    return HelloState(
      message: message ?? this.message,
      counter: counter ?? this.counter,
    );
  }
}


class HelloViewModel extends Notifier<HelloState> {
  @override
  HelloState build() {
    // 初始化默认值
    return const HelloState(message: 'hello', counter: 0);
  }



  /// 修改 message
  void updateMessage(String newMessage) {
    state = state.copyWith(message: newMessage);
  }

  /// 增加计数
  void increment() {
    state = state.copyWith(counter: state.counter + 1);
  }
}

/// 3. 对外暴露的 provider
final helloProvider =
NotifierProvider<HelloViewModel, HelloState>(HelloViewModel.new);

void main() {
  runApp(ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends ConsumerWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    print('HomePage build'); // 测试重建

    return Scaffold(
      appBar: AppBar(title: const Text('Riverpod ViewModel')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            /// 1. 监听 message，只刷新 Text
            Consumer(
              builder: (context, ref, child) {
                print('Message Text rebuild');
                final message =
                ref.watch(helloProvider.select((state) => state.message));
                return Text(
                  message,
                  style: const TextStyle(fontSize: 24),
                );
              },
            ),

            const SizedBox(height: 20),

            /// 2. 监听 counter，只刷新这个 Text
            Consumer(
              builder: (context, ref, child) {
                print('Counter Text rebuild');
                final counter =
                ref.watch(helloProvider.select((state) => state.counter));
                return Text(
                  'Counter: $counter',
                  style: const TextStyle(fontSize: 20),
                );
              },
            ),

            const SizedBox(height: 20),

            /// 3. 修改 message
            ElevatedButton(
              onPressed: () {
                ref
                    .read(helloProvider.notifier)
                    .updateMessage('world ${DateTime.now().second}');
              },
              child: const Text('改变 message'),
            ),

            const SizedBox(height: 10),

            /// 4. 增加 counter
            ElevatedButton(
              onPressed: () {
                ref.read(helloProvider.notifier).increment();
              },
              child: const Text('增加 counter'),
            ),
          ],
        ),
      ),
    );
  }
}